package com.aiyige.page.login.model.impl;

import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.Oauth2ResetPassword;
import com.aiyige.model.User;
import com.aiyige.model.request.RequestRegisterUserBody;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.login.callbacks.ILoginCallBack;
import com.aiyige.page.login.model.IResetPasswordModel;
import com.aiyige.page.login.view.IResetPasswordView;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.vondear.rxtools.RxTool;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 登录实现层
 * Created by xiachao on 17/8/10.
 */

public class ResetPasswordImplement implements IResetPasswordModel {

    IResetPasswordView view;

    @Override
    public void resetPassword(String code, String mobile, String passWord, final ILoginCallBack iLoginCallBack) {
        view.showLoading();
        ApiManager.getService().oauth2ResetPassword(code, new Oauth2ResetPassword(mobile, RxTool.Md5(passWord))).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                view.hideLoading();
                try {
                    if (response.isSuccessful()) {
                        User user = JsonUtil.toObject(response.body().string(), User.class);
                        user = new User(user);
                        AccountUtil.updateCurrentUser(user);
                        iLoginCallBack.success(user);
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call, new Throwable(data.getMessage()));
                    }

                } catch (Exception e) {
                    onFailure(call, new Throwable(response.errorBody().toString()));
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                view.hideLoading();
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    @Override
    public void setView(IResetPasswordView view) {
        this.view = view;
    }

}
